package com.whfc.hdc.redis.impl;

import com.whfc.common.util.JSONUtil;
import com.whfc.hdc.dto.AppDeviceUpgradeDTO;
import com.whfc.hdc.redis.DeviceUpgradeRedisDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2020-12-04 16:08
 */
@Repository
public class DeviceUpgradeRedisDaoImpl implements DeviceUpgradeRedisDao {

    private static final String DEVICE_UPGRADE = "device-upgrade";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void set(Integer deviceId, AppDeviceUpgradeDTO upgradeDTO) {
        String key = String.valueOf(deviceId);
        String value = JSONUtil.toString(upgradeDTO);
        redisTemplate.opsForHash().put(DEVICE_UPGRADE, key, value);
    }

    @Override
    public void set(List<Integer> deviceIdList, AppDeviceUpgradeDTO upgradeDTO) {

        String value = JSONUtil.toString(upgradeDTO);
        Map<String, String> map = new HashMap<>(deviceIdList.size());
        for (Integer deviceId : deviceIdList) {
            String key = String.valueOf(deviceId);
            map.put(key, value);
        }
        redisTemplate.opsForHash().putAll(DEVICE_UPGRADE, map);
    }

    @Override
    public AppDeviceUpgradeDTO get(Integer deviceId) {
        String key = String.valueOf(deviceId);
        String value = (String) redisTemplate.opsForHash().get(DEVICE_UPGRADE, key);
        if (!StringUtils.isEmpty(value)) {
            return JSONUtil.parseObject(value, AppDeviceUpgradeDTO.class);
        }
        return null;
    }

    @Override
    public void del(Integer deviceId) {
        String key = String.valueOf(deviceId);
        redisTemplate.opsForHash().delete(DEVICE_UPGRADE, key);
    }

    @Override
    public void del(List<Integer> deviceIdList) {

        String[] keys = new String[deviceIdList.size()];
        for (int i = 0; i < deviceIdList.size(); i++) {
            keys[i] = String.valueOf(deviceIdList.get(i));
        }
        redisTemplate.opsForHash().delete(DEVICE_UPGRADE, keys);

    }

    @Override
    public void delAll() {
        redisTemplate.delete(DEVICE_UPGRADE);
    }
}
